<template>
	<view class="flex-column container">
		<view class="search under-line padding-bottom-12" id="search" :style="searchStyle">
			<tian-search-bar :placeholder="$w('搜索商品')" bg_color="#f5f5f5" :disabled="true"
				@click="navTo('/pages/search/search')" style="padding-top:12rpx ;"></tian-search-bar>
		</view>
		<view class="main-category-panel-all ">
			<!-- 左侧主分类栏 -->
			<view class="">
				<scroll-view class="scroll-view_W" scroll-y="true" scroll-with-animation :scroll-top="mainCategoryTop">
					<view v-for="(item, index) in categories" :key="index" @click="getCurrCateData(item,index)"
						class="item" :class="[item.className]" :id="'main-'+item._id">
						<view class="text">
							<text>{{ item.name }}</text>
						</view>
					</view>

				</scroll-view>
			</view>
			<view class="flex-1 content" :class="['main-index'+mainCategory.index]">
				<!-- 主分类图广告 -->
				<view class="ad-box">
					<image :src="mainCategory.ad_banner" mode="scaleToFill" class="cate-ad" @click="adClick"></image>
				</view>
				<view class="sub-category">
					<!-- 二级分类导航 -->
					<scroll-view scroll-x="true" class="scroll-view_H" scroll-with-animation
						:scroll-left="subCategoryLeft">
						<label v-for="(item,index) in subCategories" :key="index">
							<view class="scroll-view-item_H" @click="fastSelectSubcategory(item)"
								:id="'sub-left-' + item._id" :class="{current:item.selected}">
								<!-- <view class="text">{{item.name}}</view> -->

								<view class="nav-item-text">
									<text class="text">{{item.name}}</text>
								</view>
							</view>
						</label>

					</scroll-view>
				</view>
				<!-- 右侧分类的总scroll-view -->
				<scroll-view scroll-y="true" class="scroll-h3 padding-left-20" scroll-with-animation
					@scroll="subCategoryScroll" :scroll-top="subCategoryTop">
					<view class="third-category">
						<view v-for="(item,index) in subCategories" :key="index" class="item" :id="'sub-' + item._id">
							<view class="title" @click="loadList(item)">
								<text class="">{{item.name}}</text>
							</view>
							<wjf-goods-list v-if="item.children.length==0" v-model="item.cate2Goods"></wjf-goods-list>
							<!-- 三级分类 -->
							<view v-for="(item2,index2) in item.children" :key="index2" class="sub-category-3">
								<!-- <image :src="item2.icon" mode="aspectFill" class="image"></image> -->

								<view class="category-3-title" @click="loadList(item2)"><text>{{item2.name}}</text>
								</view>
								<wjf-goods-list v-if="item2.children.length==0" v-model="item2.cate3Goods">
								</wjf-goods-list>
								<!-- 第四级 -->
								<view class="category-3-box" v-if="item2.children.length>0">
									<view class="sub-category-4" v-for="(item3,index3) in item2.children" :key="index3">
										<text>{{item3.name}}</text>
									</view>
								</view>
							</view>
							<!-- <view class="sub-items">
								<view v-for="(item2,index2) in item.children" :key="index2" class="sub-item"
									@click="loadList(item2)">
									<image :src="item2.icon" mode="aspectFill" class="image"></image>
									<text>{{item2.name}}</text>
								</view>
							</view> -->
						</view>
					</view>
				</scroll-view>
			</view>
		</view>
		<tian-goods-sku :value="goods" ref="tianSkuPop"></tian-goods-sku>
	</view>
</template>

<script>
	const db = uniCloud.database();
	const dbCmd = db.command
	// import tabbarMixin from './mixin/tabbar'
	import i18nMixin from './i18n/i18n-mixin.js'
	export default {
		mixins: [i18nMixin],
		data() {
			return {
				goods: {},
				mainCategory: {},
				categories: [],
				subCategories: [],
				subCateHeight: 100,
				subCategoryLeft: 0,
				subCategoryTop: 0,
				mainCategoryTop: 0,
				options: {
					scrollLeft: 0,
					scrollTop: 0,
					sv: "",
					mainCurrentId: "",
					subCurrentId: ""
				},
				key: 0
			};
		},
		onLoad(e) {
			if (e.id) {
				this.options.mainCurrentId = e.id;
			}
			//选中主分类触发器
			/* uni.$on('changeMainCid', (e) => {
				//默认选中id,没有点击分类之前，是没有这个事件的
				this.changeMainCategory({
					_id: e
				})
			}); */
			this.loadData()
		},
		computed: {
			goodsCondition() {
				console.log("change goods condition")
				return `category_id=="${this.options.subCurrentId}"`
			},
			searchStyle() {
				//#ifdef MP
				return `padding-top:${this.systemInfo.custom.top}px;`
				//#endif
				return ""
			}
		},
		onShow() {},
		onHide() {
			//防止弹窗隐藏了导航栏
			uni.showTabBar()
			setTimeout(() => {
				this.$refs.tianSkuPop.close();
			}, 500)
		},
		mounted() {
			// console.log('mounted');
			// const query = uni.createSelectorQuery().in(this);
			// query.select('#search').boundingClientRect(data => {
			// 	console.log(data, this.systemInfo)
			// }).exec();
			// this.loadData()
		},
		methods: {
			fastSelectSubcategory(item) {
				//快速选择二级分类
				this.subCategories.forEach(cate => {
					cate.selected = item._id == cate._id;
				})
				this.subCategoryTop = item.top
				// console.log(item)
			},
			subCategoryScroll(e) {
				//二级分类联动
				// console.log("subCategoryScroll", e.detail.scrollTop)selected
				if (e.detail.scrollTop > 0) {
					this.subCategories.forEach(cate => {
						cate.selected = false;
						if (cate.top <= e.detail.scrollTop && cate.bottom > e.detail
							.scrollTop) {
							this.subCategoryLeft = cate.left
							cate.selected = true;
						}
					})
				} else {
					this.subCategoryLeft = 0
				}
			},
			loadList(item) {
				// console.log(item);
				// getApp().globalData.searchText = text;
				uni.navigateTo({
					url: "/pages/product/list?cid=" + item._id
				})
			},
			loadData() {
				let lang = uni.getLocale()
				db.collection("tian-mall-categories").where("status==true").field(
						`_id,parent_id,locale_name["${lang}"] as name,icon,sort,ad_banner,ad_open_url`)
					.orderBy("sort asc").get({
						getTree: {
							limitLevel: 1
						}
					}).then(({
						result
					}) => {
						let firstItem = false;

						result.data.forEach((item, mIndex) => {
							item.index = mIndex;
							if (!item.ad_banner) {
								//默认广告图
								item.ad_banner =
									"https://vkceyugu.cdn.bspapp.com/VKCEYUGU-3fbab731-e993-47e6-882f-a74e444709a3/11b41427-1164-4254-a723-aacec29d1eb6.jpg";
							} else {
								item.ad_banner = this.$thumbImg(item.ad_banner, '450x150');
							}
							item.icon = this.$thumbImg(item.icon, '80x80');
							//参数传递，匹配是否正确
							if (this.options.mainCurrentId && item._id == this.options.mainCurrentId) {
								firstItem = item;
							}
							item.children.forEach((child, index) => {
								//默认第一个选中
								child.selected = index == 0
								//第三极分类的图片
								if (child.children) {
									child.children.forEach(e3 => {
										e3.icon = this.$thumbImg(e3.icon, '130x130');
									})
								}
							})
						})
						this.categories = result.data;
						if (!firstItem) {
							firstItem = this.categories[0] //设置默认为第一级
						}
						this.getCurrCateData(firstItem, 0)
						// this.changeMainCategory(firstItem)
					})
			},
			/**
			 * 广告图跳转
			 */
			adClick() {
				if (this.mainCategory.ad_open_url) {
					this.navTo(this.mainCategory.ad_open_url)
				}
			},
			/**
			 * @param {Object} firstItem
			 * 先读取当前一级分类下的全部分类数据
			 */
			getCurrCateData(firstItem, firstIndex) {
				let lang = uni.getLocale()
				this.subCategoryTop = 0;
				this.subCategoryLeft = 0;
				this.mainCategoryTop = firstItem.top - 200
				if (!firstItem.isLoaded) {
					uni.showLoading({
						title: '',
						mask: false
					});
					db.collection("tian-mall-categories").where("status==true").field(
							`_id,parent_id,locale_name["${lang}"] as name,icon,sort,ad_banner,ad_open_url`)
						.orderBy("sort asc").get({
							getTree: {
								startWith: `_id=='${firstItem._id}'`
							}
						}).then(({
							result
						}) => {
							let item = result.data[0]
							if (!item.ad_banner) {
								//默认广告图
								item.ad_banner =
									"https://vkceyugu.cdn.bspapp.com/VKCEYUGU-3fbab731-e993-47e6-882f-a74e444709a3/11b41427-1164-4254-a723-aacec29d1eb6.jpg";
							} else {
								item.ad_banner = this.$thumbImg(item.ad_banner, '450x150');
							}
							this.categories[firstIndex] = item
							this.categories[firstIndex].isLoaded = true
							uni.hideLoading()
							this.changeMainCategory(this.categories[firstIndex])
							this.getCate23Goods(firstIndex)
						})
				} else {
					this.changeMainCategory(this.categories[firstIndex])
				}

			},
			/**
			 * @param {Object} firstIndex
			 * 使用云对象获取无子分类的二三级分类最新商品(最多6个)
			 */
			getCate23Goods(firstIndex) {
				// locale_name["${lang}"] as name
				let lang = uni.getLocale()
				let cate_idArr = []
				this.categories[firstIndex].children.forEach(item2 => {
					if (!item2.children || item2.children.length == 0) cate_idArr.push(item2._id)
					item2.children.forEach(item3 => {
						if (!item3.children || item3.children.length == 0) cate_idArr.push(item3._id)
					})
				})
				db.collection('opendb-mall-goods').where({
					cid: dbCmd.in(cate_idArr)
				}).field(`_id,name["${lang}"] as locale_name,goods_thumb,cid`).orderBy('last_modify_date desc').limit(
					6).get().then(({
					result
				}) => {
					let ttGoods = result.data
					this.categories[firstIndex].children.forEach((item2) => {
						if (item2.children.length == 0) {
							this.$set(item2, 'cate2Goods', ttGoods.reduce((pre, curr) => {
								if (curr.cid.length == 2 && curr.cid[1] == item2._id) {
									pre.push({
										name: curr.locale_name,
										_id: curr._id,
										goods_thumb: curr.goods_thumb
									})
								}
								return pre
							}, []))
						}
						item2.children.forEach(item3 => {
							if (item3.children.length == 0) {
								this.$set(item3, 'cate3Goods', ttGoods.reduce((pre, curr) => {
									if (curr.cid.length == 3 && curr.cid[2] == item3
										._id) {
										pre.push({
											name: curr.locale_name,
											_id: curr._id,
											goods_thumb: curr.goods_thumb
										})
									}
									return pre
								}, []))
							}
						})
					})
				})
			},
			/**
			 * @param {Object} item
			 * 点击左侧主分类
			 */
			changeMainCategory(item) {
				let index = -1;
				this.categories.forEach((e, i) => {
					if (e._id == item._id) {
						index = i;
					}
					e.className = ""
				});
				if (index == -1) {
					//主分类id不在范围内
					console.log("主分类id不在范围内", item)
					return false;
				} else if (this.options.mainCurrentId == item._id) {
					console.log("重复点击无效", item)
					return false;
				}
				this.options.mainCurrentId = item._id
				// console.log("item._id", index, item)
				this.mainCategory = this.categories[index];
				this.mainCategory.className = "current"
				this.subCategories = this.categories[index].children;
				// this.subCateHeight = this.subCategories.length * 40;
				if (this.subCategories.length > 0) {
					this.options.subCurrentId = this.subCategories[0]._id;
					this.$nextTick(() => {
						this.fastSelectSubcategory(this.subCategories[0])
					})
				} else {
					//没有子分类，默认查询主分类商品
					this.options.subCurrentId = this.options.mainCurrentId;
				}

				if (index != 0) {
					this.categories[index - 1].className = "prev"
				}
				if (index != this.categories.length - 1) {
					this.categories[index + 1].className = "next"
				}
				setTimeout(() => {
					this.calcMainSize()
					this.calcSize()
				}, 500)
				// console.log('show-item', this.categories);
				// setTimeout(() => {
				// 	this.options.scrollLeft = index * 60 - 50;
				// 	console.log("this.options.scrollLeft", this.options.scrollLeft)
				// }, 300)
			},
			changeSubCategory(item, index) {
				this.options.subCurrentId = item._id;
				setTimeout(() => {
					this.options.scrollTop = index * 30 - 60;
					//console.log("this.options.scrollLeft", this.options.scrollTop)
				}, 300)
			},
			/**
			 * 列表上打开sku
			 * @param {Object} e
			 */
			openSku(e) {
				console.log("openSku", e)
				this.goods = e;
				this.$refs.tianSkuPop.open();
			},
			//计算右侧栏每个tab的高度等信息
			calcSize() {
				let h = 0;
				let left = 0;
				let marginLeft = 7;
				let preWidth = 0
				this.subCategories.forEach((item, index) => {
					let view = uni.createSelectorQuery().select('#sub-' + item._id);
					view.fields({
							size: true
						},
						data => {
							if (data) {
								item.top = h;
								h += data.height;
								item.bottom = h;
							}
						}
					).exec();

					//计算横向二级分类的宽度
					let viewLeft = uni.createSelectorQuery().select('#sub-left-' + item._id);
					viewLeft.fields({
							size: true
						},
						data => {
							// console.log(data)
							item.left = left + marginLeft - preWidth;
							left += data.width + marginLeft;
							preWidth = data.width;
							// if (data) {
							// 	item.top = h;
							// 	h += data.height;
							// 	item.bottom = h;
							// }
						}
					).exec();
				});

			},
			calcMainSize() {
				let h = 0;
				//计算主分类的高度
				this.categories.forEach(item => {
					let view = uni.createSelectorQuery().select('#main-' + item._id);

					view.fields({
							size: true
						},
						data => {
							if (data) {
								item.top = h;
								h += Math.round(data.height);
								item.bottom = h;
							}
						}
					).exec();
				})
			},
		}
	}
</script>

<style lang="scss">
	page {
		background: #FFFFFF;
		height: 100%;
		width: 100%;
	}

	.search {
		padding-top: var(--status-bar-height);
		// #ifdef MP
		padding-top: 0;
		// #endif
		// background: #FFFFFF;
	}

	// $windowHeight:calc(100vh - (var(--window-top)) - (var(--window-bottom)) - var(--status-bar-height));

	.container {
		// height: $windowHeight;
		display: flex;
		height: 100%;
		width: 100%;
	}

	.container>view {
		width: 100%;
	}

	.main-category-panel-all {
		padding-top: 12rpx;
		background: #f2f2f2;
		flex: 1; //原代码 __wjf
		height: calc(100vh - (var(--window-top)) - (var(--window-bottom)) - var(--status-bar-height) - 110rpx);
		// #ifdef MP
		height: calc(100vh - (var(--window-top)) - (var(--window-bottom)) - var(--status-bar-height) - 134rpx);
		// #endif
		display: flex;
		width: 100%;
		overflow-x: hidden;

	}

	.scroll-view_W {
		width: 160rpx; //修改过__wjf 原236
		height: 100%;
		text-align: center;
		background: #FFFFFF;
		// background: #f2f2f2;

		.item {
			height: 86rpx;
			padding: 0 4rpx;
			display: flex;
			text-align: left;
			align-items: center;
			justify-content: center;
			background: #f2f2f2;

			.text {
				font-size: 26rpx;
				line-height: 1.1;
				// word-break: break-all;
				text-overflow: ellipsis;
				display: -webkit-box;
				-webkit-box-orient: vertical;
				-webkit-line-clamp: 2;
				overflow: hidden;
			}
		}

		.current {
			font-weight: 600;
			background: #fff;

			.text {
				// background: #fff;
			}
		}

		.prev {
			border-radius: 0 0 16rpx 0;
			overflow: hidden;
		}

		.next {
			border-radius: 0 16rpx 0 0;
			overflow: hidden;
		}
	}

	.content {
		background: #FFFFFF;
		padding-top: 30rpx;
		border-radius: 30rpx 0 0 0;
		height: calc(100% - 30rpx);
		width: calc(100vw - 160rpx);

		&.main-index0 {
			border-radius: 0;
		}

		.ad-box {
			width: calc(100vw - 190rpx);
			margin-left: 22rpx;

			.cate-ad {
				width: 100%;
				height: 150rpx;
			}
		}
	}

	// 右侧二级导航部分
	.sub-category {
		// border-top: 2rpx solid $uni-bg-color-grey;
		// background: #EE4000;
		width: 580rpx;
		height: 80rpx;
		// padding: 10rpx 0;
		margin-left: 6rpx;
		// background-color: #008080;
		display: flex;
		overflow: hidden;
		justify-content: center;
		align-items: center;

		.scroll-view-item_H {
			// padding-left: $uni-spacing-row-base;

			&:last-child {
				margin-right: $uni-spacing-row-base;
			}

			&.current {
				.text {
					// background: $uni-red;
					color: $uni-red;
					font-weight: 600;
					// border-radius: 12rpx;
				}
			}

			height: 100%;

			.nav-item-text {
				display: flex;
				// flex-wrap: wrap;
				word-break: break-all;
				height: 70rpx;
				// line-height: 1.1;
				// align-items: center;
				text-align: center;
				// width: 100%;
				// height: 100%;
				background: $uni-bg-color-grey;

				.text {
					white-space: normal;
					// word-break:break-all;
					// background: $uni-bg-color-grey;
					font-size: 26rpx;
					line-height: 1.1;
					// height: 52rpx;
					max-width: 160rpx;
					border-radius: 14rpx;
					margin-left: 16rpx;
					padding: 10rpx 16rpx;
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 2;
					overflow: hidden;
					text-overflow: ellipsis;
				}

			}
		}

		.item {
			// display: inline-flex;
			// height: 68rpx;
			// line-height: 1.1;
			// align-items: center;
			// justify-content: center;
			// height: 86rpx;
			// text-align: center;

			&.current {

				// background: $uni-bg-color;
				.text {
					color: $uni-red;
					font-weight: 600;
				}

			}

			.nav-item-text {
				display: flex;
				height: 70rpx;
				line-height: 1.1;
				// align-items: center;
				text-align: left;
				width: 100%;
				// height: 100%;
				background: $uni-bg-color-grey;

				.text {
					white-space: normal;
					// word-break:break-all;
					// background: $uni-bg-color-grey;
					font-size: 26rpx;
					// line-height: 1.1;
					// height: 52rpx;
					max-width: 160rpx;
					border-radius: 14rpx;
					margin-left: 16rpx;
					padding: 10rpx 16rpx;
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 2;
					overflow: hidden;
					text-overflow: ellipsis;
				}
			}
		}

	}

	.scroll-h3 {
		height: calc(100% - 230rpx);
		width: 100%;
	}

	.third-category {
		padding-bottom: 60rpx;

		.item {}

		.title {
			font-weight: 600;
			padding: 14rpx 0;
			display: flex;
			justify-content: center;
			color: #EE4000;
		}

		.sub-items {
			display: flex;
			flex-wrap: wrap;
			text-align: center;
			font-size: 24rpx;
			// justify-content: space-between;
			padding-right: 30rpx;

			.sub-item {
				width: 33.33%;
			}
		}

		.image {
			width: 133rpx;
			height: 133rpx;
			display: block;
			margin: 6rpx auto;
		}

		// 三级分类总
		.sub-category-3 {
			background-color: #eee;
			border-radius: 6rpx;
			margin: 8rpx 0;
			padding-left: 6rpx;

			.category-3-title {

				color: #008080;
				font-size: 26rpx;
				padding: 12rpx 0;

			}

			.category-3-box {
				display: flex;
				flex-wrap: wrap;
				// background-color: #eee;
				padding: 10rpx 0;

				//四级分类块
				.sub-category-4 {
					margin: 10rpx;
					padding: 6rpx;
					display: flex;
					flex-wrap: wrap;
					max-width: 30%;
					line-height: 1.1;
					color: #555;
					font-size: 24rpx;
					align-items: center;
					border: 1px solid #aaa;
					border-radius: 12rpx;
				}
			}
		}

	}

	.goods-list-panel {
		width: 100%;
		height: 100%;
		flex: 1;
	}
</style>